package com.homson.servicedomain.domain.transaction;

import com.homson.coreservice.servicecommon.co.TransactionAddCO;
import com.homson.coreservice.servicecommon.enumeration.AccountTypeEnum;
import com.homson.coreservice.servicecommon.expection.BizException;
import com.homson.servicedomain.domain.account.AccountQueryCommand;
import com.homson.servicedomain.domain.user.UserQueryCommand;
import com.homson.servicedomain.message.domain.converter.TransactionEventConverter;
import com.homson.servicedomain.message.domain.model.TransactionAddedEvent;
import com.homson.servicedomain.message.domain.sender.TransactionEventSender;
import com.homson.coreservice.serviceinfrastructure.datasource.repository.account.TransactionRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author: homson_leo
 * @contact: hey_超级巨星（Homson_Leo）- 刘泓岑 1196816884@qq.com
 * @time: 2025/10/19 2:16 PM
 **/
@Service
public class TransactionAddCommand {
    
    @Resource
    private UserQueryCommand userQueryCommand;
    
    @Resource
    private AccountQueryCommand accountQueryCommand;
    
    @Resource
    private TransactionRepository transactionRepository;
    
    @Resource
    private TransactionEventSender transactionEventSender;
    
    @Transactional(rollbackFor = Exception.class)
    public void addTransaction(TransactionAddCO transactionAddCO) throws BizException {
        Boolean userExist = userQueryCommand.isUserExist(transactionAddCO.getUserId());
        if (!userExist) {
            throw new BizException("用户不存在");
        }
        AccountTypeEnum accountType = AccountTypeEnum.of(transactionAddCO.getAccountType());
        if(Objects.isNull(accountType)){
            throw new BizException("不支持的账户类型");
        }
        Boolean accountExist = accountQueryCommand.isAccountExist(transactionAddCO.getAccountId(), accountType);
        if (!accountExist) {
            throw new BizException("账户不存在");
        }
        transactionRepository.createTransaction(transactionAddCO);
        // 领域事件更新账户总额
        TransactionAddedEvent transactionAddedEvent = TransactionEventConverter.convert(transactionAddCO);
        transactionEventSender.sendTransactionAddedEvent(transactionAddedEvent);
    }

}
